package com.guojian.http.handle;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Enumeration;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.eclipse.jetty.server.Request;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class HttpJettyRequestBuilder {

	private Request httpJettyRequest;

	private String targetUrl;

	public HttpJettyRequestBuilder(Request httpJettyRequest, String targetUrl) {
		super();
		this.httpJettyRequest = httpJettyRequest;
		this.targetUrl = targetUrl;
	}

	public HttpUriRequest buildRequest() {
		HttpEntity requestEntity = new InputStreamEntity(getInputStream(getHttpJettyRequest()));
		HttpUriRequest httpUriRequest = RequestBuilder.create(getHttpJettyRequest().getMethod()).setUri(getTargetUrl()).setEntity(requestEntity).build();
		initTargetHeader(getHttpJettyRequest(), httpUriRequest);
		return httpUriRequest;
	}

	private ByteArrayInputStream getInputStream(Request httpJettyRequest) {
		try {
			return new ByteArrayInputStream(IOUtils.toByteArray(httpJettyRequest.getInputStream()));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private void initTargetHeader(Request httpJettyRequest, HttpUriRequest targetRequest) {
		Enumeration<String> headerNames = httpJettyRequest.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String headerName = (String) headerNames.nextElement();
			Enumeration<String> headerValues = httpJettyRequest.getHeaders(headerName);
			while (headerValues.hasMoreElements()) {
				String headerValue = (String) headerValues.nextElement();
				targetRequest.addHeader(headerName, headerValue);
			}
		}
		targetRequest.removeHeaders("Content-Length");// httpClient会自动计算length
		/*String contentType = httpJettyRequest.getHeader(HttpHeaders.CONTENT_TYPE);
		if (StringUtils.isNotBlank(contentType)) {
			targetRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
		}*/
	}

	@Override
	public String toString() {
		return "HttpJettyRequestBuilder [httpJettyRequest=" + httpJettyRequest + ", targetUrl=" + targetUrl + "]";
	}

}
